<template>
    <div id="page-import">
        <x-header slot="header" :title="title">
            <a slot="right" v-show="select.length>0" @click="doneClick()">完成({{select.length}})</a>
        </x-header>
        <div class="page-indexlist-wrapper">
            <mt-index-list>
                <mt-index-section v-for="(area, index) in peoplesArr" :key="index" :index="area.initial">
                    <mt-checklist v-model="select" :options="area.cells"></mt-checklist>
                </mt-index-section>
            </mt-index-list>
        </div>
    </div>
</template>
<style>
@component-namespace page {
    @component indexlist {
        @descendent desc {
            text-align: center;
            color: #666;
            padding-bottom: 5px;
        }
        @descendent wrapper {
            width: 100%;
            border-top: solid 1px #ddd;
        }
    }
}

#page-import .mint-checklist-title {
    margin: 0;
}

.mint-indexlist-navitem {
    height: 18px;
}
</style>
<script>
import Vue from 'vue';
import Mint from 'mint-ui';
import _ from 'underscore' ;

// import { Checklist } from 'mint-ui';
import 'mint-ui/lib/style.css';
import {
    XHeader,
    Actionsheet
} from 'vux'

Vue.use(Mint);

import api from '../api';

import {
    mapState,
    mapActions
} from 'vuex'

let phones = [{
    "name": "APP功能",
    "phone": "",
    "camelChars": "ABSXH",
    "fullChars": "ABinSuXiHuang",
    "demo":true
}, {
    "name": "导入通讯录",
    "phone": "",
    "camelChars": "HSYYQ",
    "fullChars": "HuoShiYong",
    "demo":true
}, {
    "name": "或使用邀请成员",
    "phone": "",
    "camelChars": "JNZ",
    "fullChars": "JiangNaoZhong",
    "demo":true
}];
export default {
    components: {
        XHeader,
        Actionsheet

    },
    computed: {
        ...mapState({
            // peoples: state => state.z43.phonesApp,
            // gid: state => state.z43.gid,
            isLoading: state => state.vux.isLoading,
            uid: state => state.vux.uid,
            addMembers: state => state.z43.addMembers,
            currMembers: state => state.z43.currMembers,
        })
    },
    data() {
        return {
            select: [],  //列表中选中的数据.  item是包含是所有属性.需要属性顺序一致.
            peoDic: {},
            title: "导入用户",
            mode:"new",
            gid:0,
            oldData:[] ,   //保存旧的关键id数据
            peoplesArr:[] ,
            selectMemDic:{},  //选中成员的dic字段数据.
            addMemDic:{},  //选中成员的dic字段数据.
            selectMem:[], //还为使用,想用来替换 getFriends中的参数 tempSelect
        };
    },
    activated(){
        this.initData() ;
    },
    methods: {
        initData(){
            console.log("initdata start") ;

            var importTime = localStorage.getItem("importTime");//判断是否直接进入
            if(importTime==undefined){
                this.$vux.toast.show({text:"请正常进入",type: 'warn'});
                setTimeout(()=>{
                    this.$router.push("/");
                },1000)
                return ;
            }

            if( _.isEmpty(this.$route.query.gid) ){
                this.mode = "new" ;
                this.title = "新增成员";
                this.gid = 0 ;
            }else if(this.$route.query.type){  // type == add del
                this.mode = this.$route.query.type ;
                this.gid = this.$route.query.gid ;
                this.title = this.mode =="add"?"添加成员":"删除成员" ;
            }
            this.setTitle(this.title);

            this.selectMemDic = {} ;            
            this.addMemDic = {} ;   
            if( this.mode == "new" || this.mode == "add"){
                // 获取好友列表
                if( this.mode == "new" ){
                    this.select = [];
                    _.each(this.addMembers, (item, key)=>{ 
                        this.selectMemDic[item.fuid + "_" + item.pid] = item ;
                        // console.log("item:",_.clone(item));
                    }); //id数组
                }else{
                    _.each(this.currMembers, (item, key)=>{ 
                        item.fuid = item.fuid || 0 ;
                        item.pid = item.pid || 0 ;
                        this.selectMemDic[item.fuid + "_" + item.pid] = item ;
                    }); //id数组
                    // console.log("this.selectMemDic",this.selectMemDic);
                }                
                this.getFriends() ;
            }else{
                // this.selectMem = _.map(this.currMembers, (item, key)=>{ 
                //     this.selectMemDic[item.fuid + "_" + item.pid] = item ;
                //     return item.id 
                // }); //id数组
                this.refreshList( this.currMembers );
            }
            console.log("initdata done") ;
        },
        doneClick() {
            let news ,dels ,nows, item ,temp, friends = [];
            if( this.mode == "new" || this.mode == "add"){                
                for (var i = this.select.length - 1; i >= 0; i--) {
                    item = this.select[i];
                    if( this.mode == "new" || (this.mode == "add" && this.selectMemDic[item.fuid + "_" + item.pid] == undefined) ){
                        temp = {// gid: this.gid,
                            nname: item.name,pid: item.pid,fuid: item.fuid 
                        } ;
                        if(this.gid>0) temp.gid = this.gid ;
                        friends.push(temp);
                    }
                };
            }
            console.log("select",this.select);
            if( this.mode == "new"){
                this.$store.commit('z43/addMembers', {list: friends });
                history.go(-1);
                return;
            }else if(this.mode == "add"){
                if(friends.length==0) return this.$vux.toast.show({text:"请选择成员",type: 'warn'});
                api.memberAdd({
                    list:friends
                }).then(data => {
                    if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                    data = data.data;
                    friends.forEach((item,index)=>{
                        item.id = data[index] ;
                        var uid = item.fuid;
                        var uidStr = uid + "";
                        var tid = uid < 100 ? (uid < 10 ? ('0' + uid) : uid) : uidStr.substring(uidStr.length - 2);
                        var temp = `//cdns.7dtime.com/heads/${tid}.jpg`;                        
                        item.head = temp;
                    })
                    this.$store.commit('z43/currMembers', {list: this.currMembers.concat(friends) });
                    this.$vux.toast.show({text: "添加成功",type: 'success'}) ;
                    history.go(-1); //返回上一页
                    return;
                })
            }else if(this.mode == "del"){
                dels = this.select ;
                if(dels.length==0) return this.$vux.toast.show({text:"请选择成员",type: 'warn'});
                api.memberDel({
                    list:dels
                }).then(data => {
                    if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                    data = data.data;
                    var list = this.currMembers.filter(item=>{ return dels.indexOf(item.id) == -1 }) ;
                    this.$store.commit('z43/currMembers', {list: list });
                    console.log("list:",list);
                    this.$vux.toast.show({text: "删除成功",type: 'success'}) ;
                    history.go(-1); //返回上一页
                    return;
                })
            }
            // console.log(news,dels,friends);
        },
        getFriends() {
            this.$store.commit('updateLoadingStatus', {isLoading: true});
            api.friends().then(data => {
                this.$store.commit('updateLoadingStatus', {isLoading: false});
				if(data == undefined) data={errmsg:"网络错误",errno:1001};
                if(data.errno != 0){
                    this.refreshList(phones,[]);
                }
                if(data.errno >0)  return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                data = data.data;
                if(data.length==0) return this.refreshList(phones);
                this.refreshList(data);
            })
            
        },
        refreshList(allList) {  //selectArr id数组
            let temp = [],tempSelect=[],
                item, peo,tempName;
            for (var i = allList.length - 1; i >= 0; i--) {
                item = allList[i];
                if( item.admin == 9 ) continue ;  //管理员不在添加和删除列表中.
                try {
                    tempName = item.nname || item.name || item.username ;
                    peo = {
                        name: tempName ,
                        phone: item.phone || "",
                        pid: item.pid ,
                        fuid: item.fuid,
                        id: item.id,
                        "camelChars": pinyin.getCamelChars( tempName ).toUpperCase(),
                        "fullChars": pinyin.getFullChars( tempName )
                    };
                    if(item.demo) peo.demo = item.demo;
                    temp.push(peo);
                } catch (e) {
                    console.log(e);
                    continue;
                }
            }
            var items = temp ;
            // if (!items || items.length == 0) {
            //     items = phones;
            // }
            this.peoDic = {} ;
            temp = []; // let temp = []; // 
            // var item;
            for (var i = items.length - 1; i >= 0; i--) { //列表哦需要lable显示内容,value作为id选择后使用.
                item = items[i];
                item.label = item.name;
                item.value = item.id;
                this.peoDic[item.id] = item;
                // if( selectArr.indexOf( item.id) != -1) tempSelect.push(item) ;
                if( item.admin >0){ // this.selectMemDic[item.fuid + "_" + item.pid] != undefined) {
                    tempSelect.push(item);
                    item.disabled = this.mode == "add"?true:false ; //禁用取消选择已有成员.
                } ;
                if(item.demo) item.disabled =true;
                if( item.admin == 9) console.log("admin:",item);
                // if( item.pid == 8) console.log("item:8 ", item) ;
            };
            this.select = tempSelect ;
            console.log("select:", tempSelect ,_.clone(this.selectMemDic)) ;
            'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').forEach(initial => {
                let cells = items.filter(phone => phone.camelChars[0] === initial);
                if (cells.length > 0) {
                    temp.push({
                        initial,
                        cells
                    });
                }
            });
            // console.log(temp);
            this.peoplesArr = temp ;
            this.$store.commit('updateLoadingStatus', {isLoading: false});
        }
    },
    mounted() {
        this.initData();
    },
    created() {
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        let listH = h - 46;
        setTimeout(function() {
            let list = document.querySelector("#page-import .mint-indexlist-content");
            list.style.height = listH + "px";
        }, 10)
    }
};
</script>
